<template>
  <view class="container">
    <view class="page-header">
      <view class="page-title">媒体组件演示</view>
      <view class="page-desc">展示各种媒体组件和交互效果</view>
    </view>

    <!-- 图片组件 -->
    <view class="section">
      <view class="section-title">图片组件</view>
      <view class="demo-card">
        <view class="image-demo">
          <view class="image-group">
            <view class="image-item">
              <text class="image-label">基础图片</text>
              <image 
                class="demo-image" 
                src="https://picsum.photos/200/200?random=1" 
                mode="aspectFit"
                @error="handleImageError"
              />
            </view>
            
            <view class="image-item">
              <text class="image-label">圆形图片</text>
              <image 
                class="demo-image circle" 
                src="https://picsum.photos/200/200?random=2" 
                mode="aspectFill"
              />
            </view>
            
            <view class="image-item">
              <text class="image-label">圆角图片</text>
              <image 
                class="demo-image rounded" 
                src="https://picsum.photos/200/200?random=3" 
                mode="aspectFill"
              />
            </view>
          </view>
          
          <view class="image-gallery">
            <view class="gallery-title">图片画廊</view>
            <view class="gallery-grid">
              <image 
                class="gallery-item" 
                v-for="(item, index) in galleryImages" 
                :key="index"
                :src="item.src" 
                mode="aspectFill"
                @click="previewImage(index)"
              />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="section">
      <view class="section-title">轮播图</view>
      <view class="demo-card">
        <view class="swiper-demo">
          <swiper 
            class="swiper" 
            :indicator-dots="true" 
            :autoplay="true" 
            :interval="3000" 
            :duration="500"
            :circular="true"
            indicator-color="rgba(255, 255, 255, 0.5)"
            indicator-active-color="#007aff"
          >
            <swiper-item v-for="(item, index) in swiperItems" :key="index">
              <view class="swiper-item" :style="{ backgroundColor: item.color }">
                <text class="swiper-icon">{{ item.icon }}</text>
                <text class="swiper-title">{{ item.title }}</text>
                <text class="swiper-desc">{{ item.desc }}</text>
              </view>
            </swiper-item>
          </swiper>
        </view>
      </view>
    </view>

    <!-- 视频组件 -->
    <view class="section">
      <view class="section-title">视频组件</view>
      <view class="demo-card">
        <view class="video-demo">
          <view class="video-container">
            <video 
              class="demo-video" 
              src="https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4"
              :controls="true"
              :autoplay="false"
              :loop="false"
              :muted="false"
              :show-center-play-btn="true"
              :show-play-btn="true"
              :show-fullscreen-btn="true"
              @play="handleVideoPlay"
              @pause="handleVideoPause"
              @ended="handleVideoEnded"
            />
          </view>
          
          <view class="video-controls">
            <button class="btn btn-primary" @click="playVideo">播放</button>
            <button class="btn btn-secondary" @click="pauseVideo">暂停</button>
            <button class="btn btn-info" @click="stopVideo">停止</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 音频组件 -->
    <view class="section">
      <view class="section-title">音频组件</view>
      <view class="demo-card">
        <view class="audio-demo">
          <view class="audio-player">
            <view class="audio-info">
              <text class="audio-title">示例音频</text>
              <text class="audio-desc">这是一个示例音频文件</text>
            </view>
            <view class="audio-controls">
              <button class="audio-btn" @click="toggleAudio">
                <text class="audio-icon">{{ isPlaying ? '⏸️' : '▶️' }}</text>
              </button>
              <view class="audio-progress">
                <view class="progress-bar">
                  <view class="progress-fill" :style="{ width: audioProgress + '%' }"></view>
                </view>
                <text class="progress-time">{{ formatTime(audioCurrentTime) }} / {{ formatTime(audioDuration) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 相机组件 -->
    <view class="section">
      <view class="section-title">相机组件</view>
      <view class="demo-card">
        <view class="camera-demo">
          <view class="camera-container">
            <camera 
              class="demo-camera" 
              :flash="cameraFlash"
              :device-position="cameraPosition"
              @error="handleCameraError"
            />
          </view>
          
          <view class="camera-controls">
            <button class="btn btn-primary" @click="takePhoto">拍照</button>
            <button class="btn btn-secondary" @click="toggleFlash">
              {{ cameraFlash === 'on' ? '关闭闪光灯' : '开启闪光灯' }}
            </button>
            <button class="btn btn-info" @click="switchCamera">
              {{ cameraPosition === 'back' ? '前置摄像头' : '后置摄像头' }}
            </button>
          </view>
          
          <view class="photo-preview" v-if="capturedPhoto">
            <text class="preview-title">拍摄的照片：</text>
            <image class="preview-image" :src="capturedPhoto" mode="aspectFit" />
          </view>
        </view>
      </view>
    </view>

    <!-- 地图组件 -->
    <view class="section">
      <view class="section-title">地图组件</view>
      <view class="demo-card">
        <view class="map-demo">
          <view class="map-container">
            <map 
              class="demo-map" 
              :latitude="mapLatitude" 
              :longitude="mapLongitude"
              :scale="mapScale"
              :markers="mapMarkers"
              :polyline="mapPolyline"
              @markertap="handleMarkerTap"
              @regionchange="handleRegionChange"
            />
          </view>
          
          <view class="map-controls">
            <button class="btn btn-primary" @click="addMarker">添加标记</button>
            <button class="btn btn-secondary" @click="clearMarkers">清除标记</button>
            <button class="btn btn-info" @click="centerMap">回到中心</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 画布组件 -->
    <view class="section">
      <view class="section-title">画布组件</view>
      <view class="demo-card">
        <view class="canvas-demo">
          <view class="canvas-container">
            <canvas 
              class="demo-canvas" 
              canvas-id="demoCanvas"
              @touchstart="handleTouchStart"
              @touchmove="handleTouchMove"
              @touchend="handleTouchEnd"
            />
          </view>
          
          <view class="canvas-controls">
            <button class="btn btn-primary" @click="clearCanvas">清除画布</button>
            <button class="btn btn-secondary" @click="changeColor">改变颜色</button>
            <button class="btn btn-info" @click="saveCanvas">保存图片</button>
          </view>
          
          <view class="color-picker">
            <view 
              class="color-item" 
              v-for="color in colors" 
              :key="color"
              :class="{ active: currentColor === color }"
              :style="{ backgroundColor: color }"
              @click="selectColor(color)"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 富文本组件 -->
    <view class="section">
      <view class="section-title">富文本组件</view>
      <view class="demo-card">
        <view class="rich-text-demo">
          <rich-text 
            class="demo-rich-text" 
            :nodes="richTextContent"
          />
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MediaDemo',
  data() {
    return {
      galleryImages: [
        { src: 'https://picsum.photos/300/200?random=1' },
        { src: 'https://picsum.photos/300/200?random=2' },
        { src: 'https://picsum.photos/300/200?random=3' },
        { src: 'https://picsum.photos/300/200?random=4' },
        { src: 'https://picsum.photos/300/200?random=5' },
        { src: 'https://picsum.photos/300/200?random=6' }
      ],
      swiperItems: [
        {
          icon: '🎨',
          title: '设计',
          desc: '精美的UI设计',
          color: '#ff6b6b'
        },
        {
          icon: '💻',
          title: '开发',
          desc: '强大的功能开发',
          color: '#4ecdc4'
        },
        {
          icon: '📱',
          title: '移动',
          desc: '优秀的移动体验',
          color: '#45b7d1'
        },
        {
          icon: '☁️',
          title: '云服务',
          desc: '稳定的云服务支持',
          color: '#96ceb4'
        }
      ],
      isPlaying: false,
      audioProgress: 0,
      audioCurrentTime: 0,
      audioDuration: 0,
      cameraFlash: 'off',
      cameraPosition: 'back',
      capturedPhoto: '',
      mapLatitude: 39.908823,
      mapLongitude: 116.397470,
      mapScale: 16,
      mapMarkers: [
        {
          id: 1,
          latitude: 39.908823,
          longitude: 116.397470,
          title: '北京天安门',
          iconPath: '/static/marker.png',
          width: 30,
          height: 30
        }
      ],
      mapPolyline: [
        {
          points: [
            { latitude: 39.908823, longitude: 116.397470 },
            { latitude: 39.909823, longitude: 116.398470 }
          ],
          color: '#007aff',
          width: 4
        }
      ],
      currentColor: '#000000',
      colors: ['#000000', '#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff'],
      richTextContent: [
        {
          name: 'div',
          attrs: {
            style: 'color: #333; font-size: 28rpx; line-height: 1.6;'
          },
          children: [
            {
              name: 'h2',
              attrs: {
                style: 'color: #007aff; font-size: 32rpx; margin-bottom: 20rpx;'
              },
              children: [
                {
                  type: 'text',
                  text: '富文本内容示例'
                }
              ]
            },
            {
              name: 'p',
              children: [
                {
                  type: 'text',
                  text: '这是一个富文本组件的演示，支持多种HTML标签和样式。'
                }
              ]
            },
            {
              name: 'ul',
              children: [
                {
                  name: 'li',
                  children: [
                    {
                      type: 'text',
                      text: '支持文本样式'
                    }
                  ]
                },
                {
                  name: 'li',
                  children: [
                    {
                      type: 'text',
                      text: '支持列表结构'
                    }
                  ]
                },
                {
                  name: 'li',
                  children: [
                    {
                      type: 'text',
                      text: '支持链接和图片'
                    }
                  ]
                }
              ]
            },
            {
              name: 'a',
              attrs: {
                href: 'https://www.example.com',
                style: 'color: #007aff; text-decoration: underline;'
              },
              children: [
                {
                  type: 'text',
                  text: '这是一个链接'
                }
              ]
            }
          ]
        }
      ]
    }
  },
  methods: {
    handleImageError(e) {
      console.log('图片加载失败:', e)
      uni.showToast({
        title: '图片加载失败',
        icon: 'none'
      })
    },
    previewImage(index) {
      const urls = this.galleryImages.map(item => item.src)
      uni.previewImage({
        current: index,
        urls: urls
      })
    },
    handleVideoPlay() {
      console.log('视频开始播放')
    },
    handleVideoPause() {
      console.log('视频暂停')
    },
    handleVideoEnded() {
      console.log('视频播放结束')
    },
    playVideo() {
      // 视频播放控制需要通过context API实现
      uni.showToast({
        title: '开始播放',
        icon: 'none'
      })
    },
    pauseVideo() {
      uni.showToast({
        title: '暂停播放',
        icon: 'none'
      })
    },
    stopVideo() {
      uni.showToast({
        title: '停止播放',
        icon: 'none'
      })
    },
    toggleAudio() {
      this.isPlaying = !this.isPlaying
      if (this.isPlaying) {
        this.startAudioProgress()
      } else {
        this.stopAudioProgress()
      }
    },
    startAudioProgress() {
      this.audioDuration = 180 // 假设音频时长3分钟
      const timer = setInterval(() => {
        if (this.isPlaying && this.audioCurrentTime < this.audioDuration) {
          this.audioCurrentTime += 1
          this.audioProgress = (this.audioCurrentTime / this.audioDuration) * 100
        } else {
          clearInterval(timer)
        }
      }, 1000)
    },
    stopAudioProgress() {
      // 停止进度更新
    },
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    },
    takePhoto() {
      const ctx = uni.createCameraContext()
      ctx.takePhoto({
        quality: 'high',
        success: (res) => {
          this.capturedPhoto = res.tempImagePath
          uni.showToast({
            title: '拍照成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.log('拍照失败:', err)
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          })
        }
      })
    },
    toggleFlash() {
      this.cameraFlash = this.cameraFlash === 'on' ? 'off' : 'on'
    },
    switchCamera() {
      this.cameraPosition = this.cameraPosition === 'back' ? 'front' : 'back'
    },
    handleCameraError(e) {
      console.log('相机错误:', e)
      uni.showToast({
        title: '相机启动失败',
        icon: 'none'
      })
    },
    addMarker() {
      const newMarker = {
        id: Date.now(),
        latitude: this.mapLatitude + (Math.random() - 0.5) * 0.01,
        longitude: this.mapLongitude + (Math.random() - 0.5) * 0.01,
        title: `标记点 ${this.mapMarkers.length + 1}`,
        iconPath: '/static/marker.png',
        width: 30,
        height: 30
      }
      this.mapMarkers.push(newMarker)
    },
    clearMarkers() {
      this.mapMarkers = []
    },
    centerMap() {
      this.mapLatitude = 39.908823
      this.mapLongitude = 116.397470
    },
    handleMarkerTap(e) {
      const marker = this.mapMarkers.find(m => m.id === e.detail.markerId)
      if (marker) {
        uni.showToast({
          title: `点击了${marker.title}`,
          icon: 'none'
        })
      }
    },
    handleRegionChange(e) {
      console.log('地图区域变化:', e.detail)
    },
    clearCanvas() {
      const ctx = uni.createCanvasContext('demoCanvas')
      ctx.clearRect(0, 0, 300, 200)
      ctx.draw()
    },
    changeColor() {
      const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff']
      this.currentColor = colors[Math.floor(Math.random() * colors.length)]
    },
    saveCanvas() {
      uni.canvasToTempFilePath({
        canvasId: 'demoCanvas',
        success: (res) => {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              uni.showToast({
                title: '保存成功',
                icon: 'success'
              })
            }
          })
        }
      })
    },
    selectColor(color) {
      this.currentColor = color
    },
    handleTouchStart(e) {
      const ctx = uni.createCanvasContext('demoCanvas')
      ctx.beginPath()
      ctx.moveTo(e.touches[0].x, e.touches[0].y)
    },
    handleTouchMove(e) {
      const ctx = uni.createCanvasContext('demoCanvas')
      ctx.setStrokeStyle(this.currentColor)
      ctx.setLineWidth(3)
      ctx.lineTo(e.touches[0].x, e.touches[0].y)
      ctx.stroke()
      ctx.draw(true)
    },
    handleTouchEnd(e) {
      // 触摸结束
    }
  }
}
</script>

<style scoped>
.page-header {
  text-align: center;
  margin-bottom: 40rpx;
}

.page-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.page-desc {
  font-size: 26rpx;
  color: #666;
}

.demo-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

/* 图片组件 */
.image-demo {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.image-group {
  display: flex;
  gap: 20rpx;
  justify-content: space-around;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15rpx;
}

.image-label {
  font-size: 24rpx;
  color: #666;
}

.demo-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
}

.demo-image.circle {
  border-radius: 50%;
}

.demo-image.rounded {
  border-radius: 20rpx;
}

.gallery-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

.gallery-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15rpx;
}

.gallery-item {
  width: 100%;
  height: 120rpx;
  border-radius: 8rpx;
}

/* 轮播图 */
.swiper-demo {
  margin: 20rpx 0;
}

.swiper {
  height: 300rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.swiper-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
}

.swiper-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.swiper-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 15rpx;
}

.swiper-desc {
  font-size: 26rpx;
  opacity: 0.9;
}

/* 视频组件 */
.video-demo {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.video-container {
  border-radius: 12rpx;
  overflow: hidden;
}

.demo-video {
  width: 100%;
  height: 300rpx;
}

.video-controls {
  display: flex;
  gap: 15rpx;
  justify-content: center;
}

/* 音频组件 */
.audio-demo {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.audio-player {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
}

.audio-info {
  margin-bottom: 20rpx;
}

.audio-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.audio-desc {
  font-size: 24rpx;
  color: #666;
}

.audio-controls {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.audio-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #007aff;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.audio-icon {
  font-size: 24rpx;
}

.audio-progress {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.progress-bar {
  height: 6rpx;
  background: #e9ecef;
  border-radius: 3rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #007aff;
  border-radius: 3rpx;
  transition: width 0.3s ease;
}

.progress-time {
  font-size: 20rpx;
  color: #666;
  text-align: right;
}

/* 相机组件 */
.camera-demo {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.camera-container {
  border-radius: 12rpx;
  overflow: hidden;
}

.demo-camera {
  width: 100%;
  height: 300rpx;
}

.camera-controls {
  display: flex;
  gap: 15rpx;
  justify-content: center;
}

.photo-preview {
  margin-top: 20rpx;
  text-align: center;
}

.preview-title {
  font-size: 26rpx;
  color: #333;
  margin-bottom: 15rpx;
  display: block;
}

.preview-image {
  width: 200rpx;
  height: 150rpx;
  border-radius: 8rpx;
}

/* 地图组件 */
.map-demo {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.map-container {
  border-radius: 12rpx;
  overflow: hidden;
}

.demo-map {
  width: 100%;
  height: 300rpx;
}

.map-controls {
  display: flex;
  gap: 15rpx;
  justify-content: center;
}

/* 画布组件 */
.canvas-demo {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.canvas-container {
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  overflow: hidden;
}

.demo-canvas {
  width: 100%;
  height: 200rpx;
  background: white;
}

.canvas-controls {
  display: flex;
  gap: 15rpx;
  justify-content: center;
}

.color-picker {
  display: flex;
  gap: 15rpx;
  justify-content: center;
  flex-wrap: wrap;
}

.color-item {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 3rpx solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
}

.color-item.active {
  border-color: #007aff;
  transform: scale(1.2);
}

/* 富文本组件 */
.rich-text-demo {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
}

.demo-rich-text {
  font-size: 26rpx;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .image-group {
    flex-direction: column;
    align-items: center;
  }
  
  .gallery-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .video-controls, .camera-controls, .map-controls, .canvas-controls {
    flex-direction: column;
  }
  
  .audio-controls {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
